package cn.ecut.tbjie.controller;

import cn.ecut.tbjie.model.Tokens;
import cn.ecut.tbjie.service.LoginService;
import cn.ecut.tbjie.service.PeopleService;
import cn.ecut.tbjie.service.TokensService;
import cn.ecut.tbjie.utils.JSONResult;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;


@RestController
@RequestMapping("/registered")
@Api(tags = "注册相关接口")
@Slf4j
public class RegisteredController {

    @Autowired
    LoginService service;

    @Autowired
    PeopleService peopleService;

    @Autowired
    TokensService tokensService;


    @PostMapping("/getras")
    @ApiOperation(value = "获取随机插入位数组")
    @ApiImplicitParam(name = "passwordDigits", value = "密码位数", required = true)
    public JSONResult getRandomAndSalt(@RequestParam("passwordDigits") Integer passwordDigits, @RequestParam("peopleName") String peopleName) {
            String random = service.getRandom(passwordDigits);
            String salt = service.getSalt();
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("randomKey", random);
            jsonObject.put("keySalt", salt);
        try {
            peopleService.writeSaltAndRandomKeyByNewPeopleName(peopleName, salt, random);
            jsonObject.put("peopleId",peopleService.getByName(peopleName).getPeopleId());
            return new JSONResult(200,true,"已成功返回randomKey",jsonObject.toString());
        } catch (Exception e) {
            return JSONResult.pNameErrorMsg();
        }
    }

    @PostMapping("/in")
    @ApiOperation(value = "用户注册")
    @ApiImplicitParams( {
        @ApiImplicitParam(name = "peopleId", value = "用户id", required = true),
        @ApiImplicitParam(name = "passwordMD5", value = "密码密文", required = true)
    })
    public JSONResult Registered(@RequestParam("peopleId") Integer peopleId, @RequestParam("passwordMD5") String peopleMD5){
        log.info("peopleId = {}, peopleMD5 = {}",peopleId,peopleMD5);
        peopleService.updatePeoplePswById(peopleId,peopleMD5);
        String salt = peopleService.getSaltById(peopleId);
        Tokens token = tokensService.saveToken(salt, peopleId);
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("token",token.getTokensValue());
        return new JSONResult(200,true,"已返回服务端token",jsonObject.toString());
    }
}
